Operator Overloading


Operators

An operator is a symbol that represents and operation between objects of a class. The basic operators are displayed in the table below. When the compiler finds any of these operators, it will call the respective operator implementation. The programmer must try to implement as many operators as the class requires. However, the programmer must implement only those operators that make sense to the objects of the class.
Un operador es un símbolo que representa una operación entre objetos de una clase. Los operadores básicos son mostrados en la tabla de abajo. Cuando el compilador encuentra cualquiera de estos operadores, este llamará la implementación respectiva del operador. El programador debe implementar tantos operadores como la clase lo requiera. Sin embargo, el programador debe implementar solamente aquellos operadores que tengan sentido para los objetos de la clase.

Symbol    Meaning    operator  
+Additionoperator+
-Substrationoperator-
*Productoperator*
/Divisionoperator/
=Copyoperator=
%Moduleoperator%
++Unit Incrementoperator++
--Unit Decrementoperator--
+=Increment with assignmentoperator+=
-=Decrement with assignmentoperator-=
*=Product with assignmentoperator*=
/=Division with assignmentoperator/=
%=Module with assignmentoperator%=
>Bigger thanoperator>
<Less thanoperator<
>=Bigger than or equaloperator>=
<=Less than or equaloperator<=
==Equaloperator==
!=Differentoperator!=
&&Andoperator&&
||Andoperator||
()Castingoperator()
[]Subscriptoperator[]
^Binary XORoperator^
^=Binary XOR with assignmentoperator^=
&Binary ANDoperator&
&=Binary AND with assignmentoperator&=
|Binary ORoperator|
|Binary OR with assignmentoperator|=
~Binary Ones Complementoperator~
<<Binary left shift operatoroperator<<
>>Binary right shift operatoroperator>>

operator=

The most important operator is operator=. As a matter of fact, a good class design requires at the least the implementation of: the copy constructor and the operator=. Additionally, if your class is going to be used with the Standard Template Library (STL), you must implement also operator<.
El operador más importante es operator=. De hecho, un buen diseño de una clase requiere al menos la implementación de: el constructor de copia y el operator=. Adicionalmente, si su clase se va a usar con la Librería Estándar de Plantillas (STL), usted debe implementar también operator<.

Problem 1
Modify the MyPoint class in the Space program by adding the copy constructor and the operator=. How many times the destructor of MyPoint class is called?
Modifique la clase MyPoint en el programa Space agregando el constructor de copia y el operator=. Cuantas veces se llama el destructor de la clase MyPoint?

MyPoint.h
#pragma once
class MyPoint
{
public:
     MyPoint(void);
     MyPoint(const MyPoint& init); // Copy constructor
     ~MyPoint(void);
     double x;
     double y;
     double GetModule();
     double GetAbsModule();
     double GetMax();
     double GetMin();
     double GetAverage();
     double GetStd();
     MyPoint& operator=(const MyPoint& init);
};

MyPoint.cpp
#include "StdAfx.h"
#include "MyPoint.h"


MyPoint::MyPoint(void)
{
     x = 0.0;
     y = 0.0;
}

MyPoint::MyPoint(const MyPoint& init) // Copy constructor
{
     //________________ 1. Constructor
     this->x = 0.0;
     this->y = 0.0;
     //________________ 2. Copy
     this->x = init.x;
     this->y = init.y;
}

MyPoint& MyPoint::operator=(const MyPoint& init)
{
     //________________ 1. Destruction of previous object
     this->x = 0.0;
     this->y = 0.0;
     //________________ 2. Copy
     this->x = init.x;
     this->y = init.y;
     //________________ 3. return *this;
     return *this;
}
. . .

Space.cpp
. . .

void Space::Window_Open(Win::Event& e)
{
     MyPoint a, b;
     a.x = 2.0;
     a.y = 3.0;
     b = a;
     Display(a);
     Display(b);
}

void Space::Display(MyPoint p)
{
     wstring text;
     Sys::Format(text, L"(%g, %g)\r\n", p.x, p.y);
     tbxOutput.Text += text;
}


operatorEqual1

operatorEqual2

operatorEqual3

Tip
The last line in the operator= must be return*this;
La última línea del operator= debe ser return*this;

operator= performance

To improve performance, the operator= can "REUSE" memory from the previous object. If dynamic memory is used in an object, the performance of the operator= can be improved by reusing the memory of the previous object, if both objects are of the same size. Thus, instead of deleting the previous object, it is possible to store the new object in the same memory as shown below.
Para mejorar el desempeño, el operator= puede "REUSAR" la memoria del objeto previo. Si memoria dinámica es usada en un objeto, el desempeño del operator= puede mejorar al reusar la memoria del objeto previo, si ambos objetos son del mismo tamaño. Así, en lugar de borrar el objeto previo, es posible almacenar el nuevo objeto en la misma memoria como se muestra debajo.

Array.cpp
. . .
Array& Array::operator=(const Array& init)
{
     //________________ 1. Resize only if needed
     if (this->size != init.size)
     {
          if (this->data != nullptr) delete [] this->data;
          data = new double[init.size];
     }
     //________________ 2. Copy
     ::memcpy(this->data, init.data, init.size*sizeof(double));
     this->size = init.size;
     //________________ 3. return *this;
     return *this;
}


Copy constructor vs. operator=

As it can be seen from the previous problem, the copy constructor and the operator= perform similar operations as shown below.

Copy Constructor
  1. Constructor
  2. Copy


operator=
  1. Destroy previous object
  2. Copy
  3. return *this;

Como se puede ver del ejemplo previo, el constructor de copia y el operador de = realizan operaciones similares como se muestra debajo.

Constructor de copia
  1. Constructor
  2. Copiar


operator=
  1. Destruir el objeto previo
  2. Copiar
  3. return *this;

Tip
As both the copy constructor and the operator= perform a copy operation, most programmer implement a private member function called Copy. Then, this function must be called from the copy constructor as well as from the operator= as shown in the code below.
Como el constructor de copia y el operador de = realizan una operación de copia, la mayoría de los programadores implementan una función miembro privada llamada Copy. Entonces, esta función debe ser llamada desde el constructor de copia y desde el operador de = como se muestra en el código debajo.

MyPoint.h
#pragma once
class MyPoint
{
public:
     MyPoint(void);
     MyPoint(const MyPoint& init); // Copy constructor
     ~MyPoint(void);
     double x;
     double y;
     double GetModule();
     double GetAbsModule();
     double GetMax();
     double GetMin();
     double GetAverage();
     double GetStd();
     MyPoint& operator=(const MyPoint& init);
private:
     void Copy(const MyPoint &init);
};

MyPoint.cpp
#include "StdAfx.h"
#include "MyPoint.h"


MyPoint::MyPoint(void)
{
     x = 0.0;
     y = 0.0;
}

MyPoint::MyPoint(const MyPoint& init) // Copy constructor
{
     //________________ 1. Constructor
     this->x = 0.0;
     this->y = 0.0;
     //________________ 2. Copy
     Copy(init);
}

MyPoint& MyPoint::operator=(const MyPoint& init)
{
     //________________ 1. Destruction of previous object
     this->x = 0.0;
     this->y = 0.0;
     //________________ 2. Copy
     Copy(init);
     //________________ 3. return *this
     return *this;
}

void MyPoint::Copy(const MyPoint &init)
{
     this->x = init.x;
     this->y = init.y;
}

MyPoint::~MyPoint(void)
{
}
...


Problem 2
Modify the MyPoint class in the Space program by adding the operator+ and the operator-.
Modifique la clase MyPoint en el programa Space agregando el operator+ y el operator-.

MyPoint.h
#pragma once
class MyPoint
{
public:
     MyPoint(void);
     MyPoint(const MyPoint& init); // Copy constructor
     ~MyPoint(void);
     double x;
     double y;
     double GetModule();
     double GetAbsModule();
     double GetMax();
     double GetMin();
     double GetAverage();
     double GetStd();
     MyPoint& operator=(const MyPoint& init);
     MyPoint operator+(const MyPoint& point) const;
     MyPoint operator-(const MyPoint& point) const;
private:
     void Copy(const MyPoint &init);
};

MyPoint.cpp
...

MyPoint MyPoint::operator+(const MyPoint& point) const
{
     MyPoint tmp;
     tmp.x = this->x + point.x;
     tmp.y = this->y + point.y;
     return tmp;
}

MyPoint MyPoint::operator-(const MyPoint& point) const
{
     MyPoint tmp;
     tmp.x = this->x - point.x;
     tmp.y = this->y - point.y;
     return tmp;
}

Space.cpp
...

void Space::Window_Open(Win::Event& e)
{
     MyPoint a, b;
     a.x = 2.0;
     a.y = 3.0;
     b.x = 1.0;
     b.y = -2.0;
     MyPoint c = a + b;
     MyPoint d = a - b;
     Display(c);
     Display(d);
}

void Space::Display(MyPoint p)
{
     wstring text;
     Sys::Format(text, L"(%g, %g)\r\n", p.x, p.y);
     tbxOutput.Text += text;
}

operatorPlus1

operatorPlus2

operatorPlus2

MyPointAddSub

Tip
It is very important to note that the equal operator returns a reference, while the summation operator and the subtraction operator return variables. Thus, the declaration of the equal operator requires an ampersand, while the summation operator and the subtraction operator do not require an ampersand to declare the variable that they return.
Es muy importante notar que el operador de igual regresa una referencia, mientras que los operadores de suma y resta regresan una variable. Así la declaración del operador de igual requiere un ampersand, mientras que los operadores de suma y resta no requieren ampersand para declarar la variable que regresan.

Tip
The figure below shows how the operator plus works. In this case, a receives a reference to b and returns the addition of the two values. Note that this reference is called point in the previous code.
La figura de abajo muestra cómo funciona el operador de mas. En este caso, a recibe una referencia a b y regresa la suma de estos dos valores. Note que esta referencia se llama point en el código previo.

OpeatorPlusDetail

Problem 3
Compute manually the output of the following program, and then test the program with your class implementation.
Calcule manualmente la salida del programa siguiente, y entonces pruebe su programa con su implementación de la clase.

Space.cpp
...

void Space::Window_Open(Win::Event& e)
{
     MyPoint a, b, c;
     a.x = 2.0;
     a.y = 3.0;
     b.x = 1.0;
     b.y = -2.0;
     c = b;
     c.x -= 2.0;
     MyPoint d = a + b - c;
     Display(c);
     Display(d);
}

void Space::Display(MyPoint p)
{
     wstring text;
     Sys::Format(text, L"(%g, %g)\r\n", p.x, p.y);
     tbxOutput.Text += text;
}


Problem 4
Modify the MyPoint class in the Space program by adding the operator++ and the operator--. Observe the specific way to implement these operators.
Modifique la clase MyPoint en el programa Space agregando el operator++ y el operator--. Observe la forma específica para implementar estos operadores.

MyPoint.h
#pragma once
class MyPoint
{
public:
     MyPoint(void);
     MyPoint(const MyPoint& init); // Copy constructor
     ~MyPoint(void);
     double x;
     double y;
     double GetModule();
     double GetAbsModule();
     double GetMax();
     double GetMin();
     double GetAverage();
     double GetStd();
     MyPoint& operator=(const MyPoint& init);
     MyPoint operator+(const MyPoint& point) const;
     MyPoint operator-(const MyPoint& point) const;
     MyPoint operator--();
     MyPoint operator--(int not_used);
     MyPoint operator++();
     MyPoint operator++(int not_used);
private:
     void Copy(const MyPoint &init);
};

MyPoint.cpp
...

MyPoint MyPoint::operator--()
{
     MyPoint tmp = *this; //save original value
     x -= 1.0;
     y -= 1.0;
     return tmp;
}

MyPoint MyPoint::operator--(int not_used)
{
     MyPoint tmp = *this; //save original value
     x -= 1.0;
     y -= 1.0;
     return tmp;
}

MyPoint MyPoint::operator++()
{
     MyPoint tmp = *this; //save original value
     x += 1.0;
     y += 1.0;
     return tmp;
}

MyPoint MyPoint::operator++(int not_used)
{
     MyPoint tmp = *this; //save original value
     x += 1.0;
     y += 1.0;
     return tmp;
}

Space.cpp
...

void Space::Window_Open(Win::Event& e)
{
     MyPoint a, b;
     a.x = 2.0;
     a.y = 3.0;
     b = a;
     a++;
     b--;
     Display(a);
     Display(b);
}

void Space::Display(MyPoint p)
{
     wstring text;
     Sys::Format(text, L"(%g, %g)\r\n", p.x, p.y);
     tbxOutput.Text += text;
}

MyPointPlusPlus

Problem 5
Compute manually the output of the following program, and then test the program with your class implementation.
Calcule manualmente la salida del programa siguiente, y entonces pruebe su programa con su implementación de la clase.

Space.cpp
...

void Space::Window_Open(Win::Event& e)
{
     MyPoint a, b;
     a.x = 2.0;
     a.y = 3.0;
     b = a;
     a.x--;
     b.y++;
     a--;
     b++;
     Display(a);
     Display(b);
     Display(a+b);
}

void Space::Display(MyPoint p)
{
     wstring text;
     Sys::Format(text, L"(%g, %g)\r\n", p.x, p.y);
     tbxOutput.Text += text;
}


Tip
Be careful of never returning a reference or a pointer to a local variable. A local variable is destroyed at the moment that the functions ends and the reference (or pointer) will make reference to an object that does not exist any longer. In the MyPoint class, if you return a reference in the plus operator (as shown below), this will avoid copying the value of tmp, and we will have a reference to a variable that has been destroyed.
Tenga cuidado de nunca regresar una referencia o un puntero a una variable local. Una variable local es destruida en el momento en que la función termina y la referencia (o el puntero) hace referencia a un objeto que ya no existe. En la clase de MyPoint, si usted regresa una referencia en el operador de mas (como se muestra debajo), esto evitará que se copie el valor de tmp, y en su lugar se tendrá una referencia a una variable que se ha destruido.

ReturningReference

Tip
In the following problema, the operator==, the operator!=, the operator<, and the operator> are declared as const to indicate that they do no change any of the member variables of the class.
En el siguiente el operator==, el operator!=, el operator< y el operator> son declarados como const para indicar que estas no cambian ninguna de las variables miembro de la clase.

Problem 6
Modify the MyPoint class in the Space program by adding the operator==, the operator!=, the operator< and the operator>.
Modifique la clase MyPoint en el programa Space agregando el operator==, el operator!=, el operator< y el operator>.

MyPoint.h
#pragma once
class MyPoint
{
public:
     MyPoint(void);
     MyPoint(const MyPoint& init); // Copy constructor
     ~MyPoint(void);
     double x;
     double y;
     double GetModule();
     double GetAbsModule();
     double GetMax();
     double GetMin();
     double GetAverage();
     double GetStd();
     MyPoint& operator=(const MyPoint& init);
     MyPoint operator+(const MyPoint& point) const;
     MyPoint operator-(const MyPoint& point) const;
     MyPoint operator--();
     MyPoint operator--(int not_used);
     MyPoint operator++();
     MyPoint operator++(int not_used);
     bool operator==(const MyPoint& point) const;
     bool operator!=(const MyPoint& point) const;
     bool operator<(const MyPoint& point) const;
     bool operator>(const MyPoint& point) const;
private:
     void Copy(const MyPoint &init);
};

MyPoint.cpp
...

bool MyPoint::operator==(const MyPoint& point) const
{
     if (this->x != point.x) return false;
     if (this->y != point.y) return false;
     return true;
}

bool MyPoint::operator!=(const MyPoint& point) const
{
     if (this->x != point.x) return true;
     if (this->y != point.y) return true;
     return false;
}

bool MyPoint::operator<(const MyPoint& point) const
{
     return (this->x < point.x) && (this->y < point.y);
}

bool MyPoint::operator>(const MyPoint& point) const
{
     return (this->x > point.x) && (this->y > point.y);
}

Space.cpp
...

void Space::Window_Open(Win::Event& e)
{
     MyPoint a, b;
     a.x = 2.0;
     a.y = 3.0;
     b.x = -5.0;
     b.y = -3.0;
     if (a == b) this->tbxOutput.Text += L"It is equal\r\n";
     if (a != b) this->tbxOutput.Text += L"It is different\r\n";
     if (a < b) this->tbxOutput.Text += L"It is less than\r\n";
     if (a > b) this->tbxOutput.Text += L"It is greater than";
}

MyPointRelational

Problem 7
Modify the MyArray class in the Space program by adding (a) the operator==, and (b) the operator!=.
Modifique la clase MyArray en el programa Space agregando (a) el operator==, y (b) el operator!=.

Space.cpp
...

void Space::Window_Open(Win::Event& e)
{
     MyArray x(5), y(6), z(5);
     int i;
     for(i = 0; i < 5; i++)
     {
          x.data[i] = 1+ i;
          z.data[i] = i + 1;
     }
     for(i = 0; i < 6; i++) y.data[i] = 2*i;
     if (x == z) tbxOutput.Text += L"x and z are equal\r\n";
     if (x == y) tbxOutput.Text += L"x and y are equal\r\n";
     if (x != z) tbxOutput.Text += L"x and z are different\r\n";
     if (x != y) tbxOutput.Text += L"x and y are different\r\n";
}


MyArrayRelational

Problem 8
Modify the MyArray class in the Space program by adding (a) the operator=, (b) the operator+, and (c) the operator-. Create another Display function as shown.
Modifique la clase MyArray en el programa Space agregando (a) el operator=, (b) el operator+, y (c) el operator-. Cree otra función Display como se muestra.

Space.cpp
...

void Space::Window_Open(Win::Event& e)
{
     MyArray x(3), z(3);
     int i;
     for(i = 0; i < 3; i++)
     {
          x.data[i] = 1+ i;
          z.data[i] = 3*i + 1;
     }
     Display(L"x", x);
     Display(L"z", z);
     MyArray a = x+z;
     Display(L"a", a);
     a = x-z;
     Display(L"a", a);
}

MyArrayAddSubEq

Problem 9
Modify the operator+ in the MyArray class to throw a text exception that indicates that the arrays cannot be added when they are not of the same size.
Modifique el operator+ del clase MyArray para aventar una excepción de texto que diga que los arreglos no se pueden sumar cuando no son del mismo tamaño.

Space.cpp
...
void Space::Window_Open(Win::Event& e)
{
     MyArray x(2);
     MyArray y(1);
     x.data[0] = 10.0;
     x.data[1] = 11.0;
     y.data[0] = 50.5;
     MyArray z;
     try
     {
          z = x + y;
     }
     catch(wchar_t* info)
     {
          this->MessageBox(info, L"Space", MB_OK | MB_ICONERROR);
     }
}

ArrayException

Problem 10
Modify the ComplexNumb class in the Space program by adding (a) the operator==, and (b) the operator!=.
Modifique la clase ComplexNumb en el programa Space agregando (a) el operator==, y (b) el operator!=.

ComplexNumbRelational

Space.cpp
...

void Space::Window_Open(Win::Event& e)
{
     ComplexNumb x(1, 2), y(2, 3), z(1, 2);
     if (x == y) tbxOutput.Text += L"x and y are equal\r\n";
     if (x == z) tbxOutput.Text += L"x and z are equal\r\n";
     if (x != y) tbxOutput.Text += L"x and y are different\r\n";
     if (x != z) tbxOutput.Text += L"x and z are different\r\n";
}


Problem 11
Modify the ComplexNumb class in the Space program by adding (a) the operator+, (b) the operator-, (a) the operator*, and (c) the operator/. Create another Display function as shown.
Modifique la clase ComplexNumb en el programa Space agregando (a) the operator+, (b) el operator-, (a) el operator*, y (c) el operator/. Cree otra función Display como se muestra.

ComplexOpert

ComplexNumbArit

Space.cpp
...

void Space::Window_Open(Win::Event& e)
{
     ComplexNumb y(2, 3), z(1, 2);
     Display(L"y+z", y + z);
     Display(L"y-z", y - z);
     Display(L"y*z", y * z);
     Display(L"y/z", y / z);
}


Problem 12
Modify the MyText class in the Space program by adding (a) the operator==, and (b) the operator!=.
Modifique la clase MyText en el programa Space agregando (a) el operator==, y (b) el operator!=.

Space.cpp
...

void Space::Window_Open(Win::Event& e)
{
     MyText a(L"Hola"), b(L" Friend"), c(L"Hola");
     if (a == b) tbxOutput.Text += L"a is equal to b\r\n";
     if (a == c) tbxOutput.Text += L"a is equal to c\r\n";
     if (a != b) tbxOutput.Text += L"a is different to b\r\n";
     if (a != c) tbxOutput.Text += L"a is different to c\r\n";
}

MyTextRelational

Problem 13
Modify the MyText class in the Space program by adding (a) the operator=, and (b) the operator+=.
Modifique la clase MyText en el programa Space agregando (a) the operator=, y (b) el operator+=.

MyText.h
class MyText
{
...
     MyText& operator+=(const& MyText init);
};


MyText.cpp

MyText& MyText::operator+=(const& MyText init)
{
     ...
     return *this;
}


Space.cpp
...

void Space::Window_Open(Win::Event& e)
{
     MyText a(L"Hola"), b(L" Friend");
     MyText c;
     c = a;
     c += b;
     tbxOutput.Text = c.Get();
}

MyTextPlusEqual

Tip
JavaIn java by default all objects are managed using reference, therefore you have to use the new operator to create an object. Note that when the equal operator is used, no object is created; to create a new object you must use the clone function of the object. See example below.
En Java por defecto todos los objetos se manejan por medio de referencias, por lo tanto se tiene que usar el operador de new para crear un objeto. Note que cuando se usa el operador de igual no se crea un nuevo objeto; para crear un nuevo objeto se usa la función clone del objeto. Ver el ejemplo de abajo.

Box.java
public class Box
{
     public Box()
     {
     }
};


Program.java
public class Program
{
     public Program()
     {
          Box b; // The constructor of box is not being called
          Box a = new Box(); // The constructor of box is called
          int x; // It is not necessary to use new
          Box c = a; // a and c are the same object
          Box d = a.Clone(); // d is copy of a
     }
};

java.lang.Clonable Interface

In order to be able to clone an object, the class must be implement the Clonable the interface. It can be said that this interface is the equivalent of the equal operator in C++.
A fin de que un objeto se pueda clonar, la clase debe implementar la interface Clonable. Se puede decir que esta interface es el equivalente del operador de igual en C++.

Operator Overloading in Java

Java uses Interfaces to provide the same functionality of operator overloading in C++. For instance, java.lang.Comparable() interface is used to compare two objects.
Java utiliza las interfaces para proporcionar la funcionalidad de la sobrecarga de los operadores en C++. Por ejemplo, la interface java.lang.Comparable() es usada para comparar dos objetos.

© Copyright 2000-2021 Wintempla selo. All Rights Reserved. Jul 22 2021. Home